package Filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Cookie implements Filter {

	public Cookie(String string, String object) {
		// TODO 自动生成的构造函数存根
	}

	@Override
	public void destroy() {
		// TODO 自动生成的方法存根

	}

	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
			throws IOException, ServletException {
		HttpServletResponse response = (HttpServletResponse) arg1;
		HttpServletRequest req = (HttpServletRequest) arg0;
		String path = req.getServletPath();
		if (path.equals("NewsClassify") || path.equals("/Login") || path.endsWith(".js") || path.endsWith(".css")
				|| path.endsWith(".gif") || path.endsWith(".jpg")) {
			arg2.doFilter(req, arg1);
			return;
		}
		String object = (String) req.getSession().getAttribute("user_name");
		if (object == null) {
			req.setAttribute("mgs", "你没有权限访问此页");
			arg0.getRequestDispatcher("NewsClassify").forward(req, arg1);
			return;

		} else if (!object.trim().equals("")) {

			javax.servlet.http.Cookie cookie = new javax.servlet.http.Cookie("name", object);
			cookie.setMaxAge(30);
			response.addCookie(cookie);

		} else {
			javax.servlet.http.Cookie[] cookies = req.getCookies();
			if (cookies != null && cookies.length > 0) {
				for (javax.servlet.http.Cookie cookie : cookies) {
					String cookieName = cookie.getName();
					if ("name".equals(cookieName)) {
						String val = cookie.getValue();
						object = val;
					}
				}
			}
		}
		arg2.doFilter(req, arg1);

	}

	private void setMaxAge(int i) {
		// TODO 自动生成的方法存根

	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO 自动生成的方法存根

	}

}
